using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using Microsoft.Extensions.Options;
using System.Text;
using Lzfy_Refund_Service.Services;
using Lzfy_Refund_Service.Models;
using Lzfy_Refund_Service.Models.Configuration;
using Lzfy_Refund_Service.Repositories;
using Lzfy_Refund_Service.Middleware;
using Serilog;

// 配置Serilog
Log.Logger = new LoggerConfiguration()
    .ReadFrom.Configuration(new ConfigurationBuilder()
        .AddJsonFile("appsettings.json")
        .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)
        .Build())
    .CreateLogger();

try
{
    Log.Information("启动应用程序");
    
    // 全局忽略SSL证书验证（适用于所有HTTPS请求）
    System.Net.ServicePointManager.ServerCertificateValidationCallback = 
        (sender, cert, chain, errors) => true;
    
    var builder = WebApplication.CreateBuilder(args);
    
    // 显式加载微信配置文件
    builder.Configuration.AddJsonFile("appsettings.WeChat.json", optional: true, reloadOnChange: true);
    
    // 使用Serilog作为日志提供程序
    builder.Host.UseSerilog();

// Add services to the container.
builder.Services.AddControllers();

// 配置文件存储选项
builder.Services.Configure<FileStorageOptions>(builder.Configuration.GetSection("FileStorage"));

// 配置密码更新任务选项
builder.Services.Configure<PasswordUpdateTaskOptions>(builder.Configuration.GetSection("PasswordUpdateTask"));
builder.Services.Configure<HealthCheckOptions>(builder.Configuration.GetSection("HealthCheck"));
builder.Services.Configure<StabilityOptions>(builder.Configuration.GetSection("Stability"));

// 注册数据库配置服务
builder.Services.AddSingleton<IDatabaseConfigurationService, DatabaseConfigurationService>();

// 配置数据库连接工厂 - 使用弹性连接工厂提高稳定性
builder.Services.AddSingleton<IDbConnectionFactory>(provider => 
{
    var dbConfig = provider.GetRequiredService<IDatabaseConfigurationService>();
    var logger = provider.GetRequiredService<ILogger<ResilientSqlConnectionFactory>>();
    return new ResilientSqlConnectionFactory(dbConfig.GetDefaultConnection(), logger);
});

// 配置Oracle HIS数据库连接 - 使用弹性连接工厂提高稳定性
builder.Services.AddSingleton<IOracleConnectionFactory>(provider => 
{
    var dbConfig = provider.GetRequiredService<IDatabaseConfigurationService>();
    var logger = provider.GetRequiredService<ILogger<ResilientOracleConnectionFactory>>();
    return new ResilientOracleConnectionFactory(dbConfig.GetHisOracleConnection(), logger);
});

// 配置Oracle HIS DG数据库连接 - 只读库，使用弹性连接工厂
builder.Services.AddSingleton<IHisDGOracleConnectionFactory>(provider => 
{
    var dbConfig = provider.GetRequiredService<IDatabaseConfigurationService>();
    var logger = provider.GetRequiredService<ILogger<ResilientHisDGOracleConnectionFactory>>();
    return new ResilientHisDGOracleConnectionFactory(dbConfig.GetHisDGOracleConnection(), logger);
});

// 配置验证码数据库连接
builder.Services.AddSingleton<IVerifyDbConnectionFactory, VerifyDbConnectionFactory>();

// 注册仓储和服务
builder.Services.AddScoped<IUserRepository, UserRepository>();
builder.Services.AddScoped<IRefundMasterRepository, RefundMasterRepository>();
builder.Services.AddScoped<IRefundAttachRepository, RefundAttachRepository>();
builder.Services.AddScoped<IRefundDictRepository, RefundDictRepository>();
builder.Services.AddScoped<IPatientInfoRepository, PatientInfoRepository>();
builder.Services.AddScoped<IVerifyInfoRepository, VerifyInfoRepository>();
builder.Services.AddScoped<IPatientRefundPasswordRepository, PatientRefundPasswordRepository>();
builder.Services.AddScoped<IPasswordUpdateTaskRepository, PasswordUpdateTaskRepository>();

// 权限管理相关仓储
builder.Services.AddScoped<IRoleRepository, RoleRepository>();
builder.Services.AddScoped<IPermissionRepository, PermissionRepository>();

// 银行信息管理相关仓储和服务
builder.Services.AddScoped<IBankInfoRepository, BankInfoRepository>();

// 退款审核工作记录相关仓储和服务
builder.Services.AddScoped<IRefundAcctRepository, RefundAcctRepository>();

// 线上退费记录相关仓储
builder.Services.AddScoped<IPrepayRefundDetailRepository, PrepayRefundDetailRepository>();

// UUM用户管理相关仓储
builder.Services.AddScoped<IUumUserRepository, UumUserRepository>();
builder.Services.AddScoped<IUumUserModifyLogRepository, UumUserModifyLogRepository>();

// 退费任务相关仓储
builder.Services.AddScoped<IRefundTaskMasterRepository, RefundTaskMasterRepository>();
builder.Services.AddScoped<IRefundTaskDetailRepository, RefundTaskDetailRepository>();

// 通话记录相关仓储
builder.Services.AddScoped<ICallLogRepository, CallLogRepository>();

// 退费情况查询相关仓储
builder.Services.AddScoped<IRefundStatusRepository, RefundStatusRepository>();

// 门诊患者就诊信息相关仓储
builder.Services.AddScoped<IOutpPatientVisitRepository, OutpPatientVisitRepository>();

// 退费任务完成情况相关仓储
builder.Services.AddScoped<IRefundTaskCompletionStatusRepository, RefundTaskCompletionStatusRepository>();

// 服务层
builder.Services.AddScoped<IAuthService, AuthService>();
builder.Services.AddScoped<IRefundService, RefundService>();
builder.Services.AddScoped<IPatientInfoService, PatientInfoService>();
builder.Services.AddScoped<IHisPatientBalanceService, HisPatientBalanceService>();
builder.Services.AddScoped<IVerifyInfoService, VerifyInfoService>();
builder.Services.AddScoped<IBankInfoService, BankInfoService>();
builder.Services.AddScoped<IPatientRefundPasswordService, PatientRefundPasswordService>();
builder.Services.AddScoped<IPasswordUpdateTaskService, PasswordUpdateTaskService>();
builder.Services.AddScoped<IRefundProcessService, RefundProcessService>();

// 权限管理相关服务
builder.Services.AddScoped<IRoleService, RoleService>();
builder.Services.AddScoped<IUserManagementService, UserManagementService>();
builder.Services.AddScoped<IPermissionService, PermissionService>();

// 退款审核工作记录服务
builder.Services.AddScoped<IRefundAcctService, RefundAcctService>();

// 线上退费记录服务
builder.Services.AddScoped<IPrepayRefundDetailService, PrepayRefundDetailService>();

// UUM用户管理服务
builder.Services.AddScoped<IUumUserService, UumUserService>();
builder.Services.AddScoped<IUumUserModifyLogService, UumUserModifyLogService>();

// 退费任务相关服务
builder.Services.AddScoped<IRefundTaskMasterService, RefundTaskMasterService>();
builder.Services.AddScoped<IRefundTaskDetailService, RefundTaskDetailService>();

// 通话记录相关服务
builder.Services.AddScoped<ICallLogService, CallLogService>();

// 退费任务完成情况相关服务
builder.Services.AddScoped<IRefundTaskCompletionStatusService, RefundTaskCompletionStatusService>();

// 退费情况查询相关服务
builder.Services.AddScoped<IRefundStatusService, RefundStatusService>();

// Redis服务
builder.Services.AddSingleton<IRedisService, RedisService>();

// 门诊患者就诊信息相关服务
builder.Services.AddScoped<IOutpPatientVisitService, OutpPatientVisitService>();

// 患者数据查询服务
builder.Services.AddScoped<IPatientDataQueryService, PatientDataQueryService>();

// 定时任务服务
builder.Services.AddHostedService<OutpPatientVisitSyncTask>();

// 用户行为监控相关服务 - 已注释
// builder.Services.AddScoped<IUserBehaviorRepository, UserBehaviorRepository>();
// builder.Services.AddScoped<IUserBehaviorService, UserBehaviorService>();

// 注册微信配置
builder.Services.Configure<WeChatConfiguration>(builder.Configuration.GetSection(WeChatConfiguration.SectionName));

// 微信推送通知服务 - 使用命名HttpClient避免生命周期问题
builder.Services.AddHttpClient("WeChatClient", (serviceProvider, client) =>
{
    // 从配置中读取超时时间
    var weChatConfig = serviceProvider.GetRequiredService<IOptions<WeChatConfiguration>>().Value;
    client.Timeout = TimeSpan.FromSeconds(weChatConfig.TimeoutSeconds);
})
.ConfigurePrimaryHttpMessageHandler(() =>
{
    var handler = new HttpClientHandler();
    // 跳过SSL证书验证（适用于内网环境）
    handler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true;
    return handler;
});
builder.Services.AddScoped<IWeChatNotificationService, WeChatNotificationService>();

// 注册后台服务
builder.Services.AddSingleton<PasswordUpdateBackgroundService>();
builder.Services.AddHostedService<PasswordUpdateBackgroundService>(provider => provider.GetRequiredService<PasswordUpdateBackgroundService>());
builder.Services.AddSingleton<DatabaseHealthCheckService>();
builder.Services.AddHostedService<DatabaseHealthCheckService>(provider => provider.GetRequiredService<DatabaseHealthCheckService>());
builder.Services.AddSingleton<ApplicationHealthCheckService>();
builder.Services.AddHostedService<ApplicationHealthCheckService>(provider => provider.GetRequiredService<ApplicationHealthCheckService>());

// 配置JWT认证
var jwtKey = builder.Configuration["Jwt:Key"] ?? "your-super-secret-jwt-key-that-is-at-least-32-characters-long";
var key = Encoding.ASCII.GetBytes(jwtKey);

builder.Services.AddAuthentication(x =>
{
    x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x =>
{
    x.RequireHttpsMetadata = false;
    x.SaveToken = true;
    x.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = new SymmetricSecurityKey(key),
        ValidateIssuer = false,
        ValidateAudience = false,
        ClockSkew = TimeSpan.Zero
    };
});

// 配置CORS
builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowWebAdmin", policy =>
    {
        policy.SetIsOriginAllowed(origin =>
        {
            // 允许空origin（用于Swagger UI等同源请求）
            if (string.IsNullOrEmpty(origin)) return true;
            
            try
            {
                var uri = new Uri(origin);
                var host = uri.Host;
                
                // 允许localhost
                if (host == "localhost" || host == "127.0.0.1")
                    return true;
                    
                // 允许指定的内网IP段
                if (host.StartsWith("10.") || 
                    host.StartsWith("192.168.") || 
                    host.StartsWith("197.100."))
                    return true;
                    
                // 允许指定的域名
                if (host == "his-refund.his.lzsfy.com" || 
                    host.EndsWith(".lzsfy.com") ||
                    host == "www.lzetyy.com" ||
                    host.EndsWith(".lzetyy.com"))
                    return true;
                    
                return false;
            }
            catch
            {
                return false;
            }
        })
        .AllowAnyHeader()
        .AllowAnyMethod()
        .AllowCredentials();
    });
    
    // 添加专门用于Swagger的CORS策略
    options.AddPolicy("AllowSwagger", policy =>
    {
        policy.AllowAnyOrigin()
              .AllowAnyHeader()
              .AllowAnyMethod();
    });
});

// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "退费申请服务API", Version = "v1" });
    
    // 添加JWT认证配置
    c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
    {
        Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
        Name = "Authorization",
        In = ParameterLocation.Header,
        Type = SecuritySchemeType.Http,
        Scheme = "Bearer",
        BearerFormat = "JWT"
    });
    
    c.AddSecurityRequirement(new OpenApiSecurityRequirement()
    {
        {
            new OpenApiSecurityScheme
            {
                Reference = new OpenApiReference
                {
                    Type = ReferenceType.SecurityScheme,
                    Id = "Bearer"
                }
            },
            new List<string>()
        }
    });
});

var app = builder.Build();

    // Configure the HTTP request pipeline.
    // 启用Swagger在所有环境
    app.UseSwagger();
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "退费申请服务API v1");
        c.RoutePrefix = string.Empty; // Swagger UI在根路径
    });

    // app.UseHttpsRedirection(); // 暂时禁用HTTPS重定向

    // 使用CORS策略
    app.UseCors("AllowWebAdmin");
    
    // 为Swagger UI添加额外的CORS支持
    app.Use(async (context, next) =>
    {
        if (context.Request.Path.StartsWithSegments("/swagger") ||
            context.Request.Path.StartsWithSegments("/api"))
        {
            context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
            context.Response.Headers.Add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
            context.Response.Headers.Add("Access-Control-Allow-Headers", "Content-Type, Authorization");
            
            if (context.Request.Method == "OPTIONS")
            {
                context.Response.StatusCode = 200;
                return;
            }
        }
        await next();
    });
    
    // 注册全局异常处理中间件
    app.UseMiddleware<GlobalExceptionHandlingMiddleware>();

    app.UseAuthentication();
    app.UseAuthorization();

    app.MapControllers();
    Log.Information("服务配置完成，开始启动...");
    app.Run();
}
catch (Exception ex)
{
    Log.Fatal(ex, "应用程序启动失败");
    throw;
}
finally
{
    Log.CloseAndFlush();
}